1.Lambda表达式

image-20190321081123734


1
2
3
4
5
6
7
8
List<Employee> employees = Arrays.asList(
new Employee("w1", 213, 1),
new Employee("w2", 2142, 3),
new Employee("w3", 212, 2),
new Employee("w4", 2123, 21),
new Employee("w5", 214, 2132421),
new Employee("w6", 212, 2123421)
);
1
2
3
4
5
6
7
8
9
10
11
12
13
//需求获取当前公司员工年龄大于35的员工信息
public List<Employee> filterEmployees(List<Employee> list) {
//申明一个list集合存放东西
List<Employee> emps = new ArrayList<>();
//2 遍历
for (Employee emp : list) {
if (emp.getAge() >= 35) {
emps.add(emp);
}
}
//返回回去
return emps;
}
1
2
3
4
5
6
7
@Test
public void test() {
List<Employee> employ = filterEmployees(employees);
for (Employee employee : employ) {
System.out.println(employee);
}
}
1
2
3
4
5
6
7
8
9
public List<Employee> filterEmployee(List<Employee> list, Mypredicate<Employee> mp) {
List<Employee> employ = new ArrayList<>();
for (Employee employee : list) {
if (mp.test(employee)) {
employ.add(employee);
}
}
return employ;
}
1
2
3
4
public interface Mypredicate<T> {

public boolean test(T t);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
   // 方法2 匿名内部类
@Test
public void teste() {
List<Employee> list = filterEmployee(employees, new Mypredicate<Employee>() {
@Override
public boolean test(Employee o) {
return o.getSalary() <= 90;
}
});
for (Employee employee : list) {
System.out.println(employee);
}
}
1
2
3
4
5
6
7
8
//3 方法3 Lambda表达式
@Test
public void t2est() {
List<Employee> employees = filterEmployee(this.employees, (e) -> e.getSalary() <= 90);
employees.forEach(System.out::println);
System.out.println("============================");
System.out.println(employees);
}
1
2
3
4
5
6
7
8
9
10
//优化方式4 所有的都没有 只有集合有
@Test
public void test7() {
employees.stream().filter((e) -> e.getSalary() >= 90)
.limit(2)
.forEach(System.out::println);

employees.stream().map(Employee::getName).forEach(System.out::println);

}

2.Labbda 表达式

image-20190321172803824

image-20190321173010638


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

/*
* 一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
* 箭头操作符将 Lambda 表达式拆分成两部分:
*
* 左侧:Lambda 表达式的参数列表
* 右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
*
* 语法格式一:无参数,无返回值
* () -> System.out.println("Hello Lambda!");
*
* 语法格式二:有一个参数,并且无返回值
* (x) -> System.out.println(x)
*
* 语法格式三:若只有一个参数,小括号可以省略不写
* x -> System.out.println(x)
*
* 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
* Comparator<Integer> com = (x, y) -> {
* System.out.println("函数式接口");
* return Integer.compare(x, y);
* };
*
* 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
* Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
*
* 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
* (Integer x, Integer y) -> Integer.compare(x, y);
*
* 上联:左右遇一括号省
* 下联:左侧推断类型省
* 横批:能省则省
*
* 二、Lambda 表达式需要“函数式接口”的支持
* 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
* 可以检查是否是函数式接口
*/
public class TestLambda2 {

@Test
public void test1(){
int num = 0;//jdk 1.7 前,必须是 final

Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!" + num);
}
};

r.run();

System.out.println("-------------------------------");

Runnable r1 = () -> System.out.println("Hello Lambda!");
r1.run();
}

@Test
public void test2(){
Consumer<String> con = x -> System.out.println(x);
con.accept("我大尚硅谷威武!");
}

@Test
public void test3(){
Comparator<Integer> com = (x, y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
};
}

@Test
public void test4(){
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
}

@Test
public void test5(){
// String[] strs;
// strs = {"aaa", "bbb", "ccc"};

List<String> list = new ArrayList<>();

show(new HashMap<>());
}

public void show(Map<String, Integer> map){

}

//需求:对一个数进行运算
@Test
public void test6(){
Integer num = operation(100, (x) -> x * x);
System.out.println(num);

System.out.println(operation(200, (y) -> y + 200));
}

public Integer operation(Integer num, MyFun mf){
return mf.getValue(num);
}
}

Lambda 练习

image-20190322160351739

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Lambda 表达式 练习
@Test
public void test1() {
Collections.sort(emps, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
if (o1.getAge() == o2.getAge()) {
return o1.getName().compareTo(o2.getName());
} else {
return Integer.compare(o1.getAge(), o2.getAge());
}
}
});
for (Employee employee : emps) {
System.out.println(employee + "Hello world");
}
}

@Test
public void test11() {
Collections.sort(emps, (e1, e2) -> {
if (e1.getAge() == e2.getAge()) {
return e1.getName().compareTo(e2.getName());
} else {
return Integer.compare(e1.getAge(), e2.getAge());
}
});
for (Employee emp : emps) {
System.out.println(emp);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@FunctionalInterface
public interface MyFunction {

public String getValue(String str);
}



//用于处理字符串
public String strHandler(String str, MyFunction myFunction) {
return myFunction.getValue(str);
}



@Test
public void testMyFunction() {
String s = strHandler("Hello World", (str) -> str.toUpperCase());
System.out.println(s);
}

#3.java 8四大核心内置函数式接口

image-20190323101719326


image-20190323102952374


https://blog.csdn.net/qq_38958113/article/details/82909615

Consumer 消费型接口

1
2
3
4
5
6
7
8
9
10
//Consumer<T> 消费型接口

@Test
public void test1() {
happy(20, (m) -> System.out.println("消费" + m));
}

public void happy(double money, Consumer<Double> con) {
con.accept(money);
}

笔记

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* Java8 内置的四大核心函数式接口
*
* Consumer<T> : 消费型接口
* void accept(T t);
*
* Supplier<T> : 供给型接口
* T get();
*
* Function<T, R> : 函数型接口
* R apply(T t);
*
* Predicate<T> : 断言型接口
* boolean test(T t);
*
*/
public class TestLambda3 {

//Predicate<T> 断言型接口:
@Test
public void test4(){
List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
List<String> strList = filterStr(list, (s) -> s.length() > 3);

for (String str : strList) {
System.out.println(str);
}
}

//需求:将满足条件的字符串,放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
List<String> strList = new ArrayList<>();

for (String str : list) {
if(pre.test(str)){
strList.add(str);
}
}

return strList;
}

//Function<T, R> 函数型接口:
@Test
public void test3(){
String newStr = strHandler("\t\t\t 我大尚硅谷威武 ", (str) -> str.trim());
System.out.println(newStr);

String subStr = strHandler("我大尚硅谷威武", (str) -> str.substring(2, 5));
System.out.println(subStr);
}

//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}

//Supplier<T> 供给型接口 :
@Test
public void test2(){
List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));

for (Integer num : numList) {
System.out.println(num);
}
}

//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer> list = new ArrayList<>();

for (int i = 0; i < num; i++) {
Integer n = sup.get();
list.add(n);
}

return list;
}

//Consumer<T> 消费型接口 :
@Test
public void test1(){
happy(10000, (m) -> System.out.println("你们刚哥喜欢大宝剑,每次消费:" + m + "元"));
}

public void happy(double money, Consumer<Double> con){
con.accept(money);
}
}

4.方法引用与构造起引用

image-20190323115817900


5.Stream

image-20190329214435392


image-20190329214457107


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 一。Stream 的三个操作步骤
* <p>
* 1.创建Stream
* 2。中间操作
* 3。终止操作(终端操作)
*/
public class TestStreamAPi {
//创建Stream
@Test
public void test1() {
//1.可以通过Collection系列集合提供的Stream()或parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();
//2.通过Arrays中的静态方法stream()获取数组流

Employee[] emps = new Employee[10];
Stream<Employee> stream2 = Arrays.stream(emps);
//3.通过Stream中的静态方法 of()
Stream<String> stream3 = Stream.of("aa", "bb", "bb");
//4 创建无限流

//迭代
Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
stream4.limit(4).forEach(System.out::println);

//生成
Stream.generate(() -> Math.random()).limit(14).forEach(System.out::println);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class TestStreamApi2 {


List<Employee> employees = Arrays.asList(
new Employee(102, "李四", 59, 6666),
new Employee(101, "张三", 18, 9999),
new Employee(103, "王五", 28, 3333),
new Employee(104, "赵六", 8, 7777)
);
//中间操作

/**
* 1 filter--接受Lambda 从六种排除某些元素
* 2 limit --截断流 使其元素不超过给定数量
* 3 skip(n)--跳过元素 返回一个扔掉了前n个元素的流 诺流中元素不足n个 则
* 返回一个空流 与limit(n)互补
* 4 distinct--- 筛选 通过流所生成元素的hashCode()和equals()去除重复元素
*/

//内部迭代 迭代由Stream API 完成
@Test
public void test1() {
//中间操作:不会执行任何操作
Stream<Employee> employeeStream = employees.stream().filter((e) -> {
return e.getAge() > 35;
});
//终止操作:一次性执行全部内容 即惰性求值
employeeStream.forEach(System.out::println);
}

//外部迭代
@Test
public void test2() {
Iterator<Employee> iterator = employees.iterator();
while (iterator.hasNext()) {
System.out.println(iterator);
}
}

@Test
public void test3() {
employees.stream().filter((e) -> {
return e.getSalary() > 20;
}).limit(2)
.forEach(System.out::println);
}

@Test
public void test4() {
employees.stream().filter((e) -> {
return e.getSalary() > 5000;
}).skip(2).forEach(System.out::println);
}

@Test
public void test5() {
employees.stream().filter((e) -> {
return e.getSalary() > 90;
}).skip(2).distinct().forEach(System.out::println);
}
//distinct 重写equales 和hashcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class TestStreamApi3 {

List<Employee> employees = Arrays.asList(
new Employee(102, "李四", 59, 6666),
new Employee(101, "张三", 18, 9999),
new Employee(103, "王五", 28, 3333),
new Employee(104, "赵六", 8, 7777)
);

//2. 中间操作
/*
映射
map——接收 Lambda , 将元素转换成其他形式或提取信息。
接收一个函数作为参数,该函数会被应用到每个元素上,
并将其映射成一个新的元素。
flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

*/
@Test
public void test1() {
List<String> list = Arrays.asList("a", "vc", "va");
list.stream().map((str) -> str.toUpperCase()).forEach(System.out::println);
System.out.println("........................");
employees.stream().map(
Employee::getAge
).forEach(System.out::println);
System.out.println("........................");
Stream<Stream<Character>> streamStream = list.stream().map(TestStreamApi3::filterCharcter);
streamStream.forEach((sm) -> {
sm.forEach(System.out::println);
});

System.out.println("........................");

Stream<Character> characterStream = list.stream().flatMap(TestStreamApi3::filterCharcter);

}

@Test
public static Stream<Character> filterCharcter(String str) {
List<Character> list = new ArrayList<>();
for (Character ch : str.toCharArray()) {
list.add(ch);
}
return list.stream();
}

}

6 排序

image-20190401125031859


7 Stream终止操作

image-20190401125111823


image-20190401125126038


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class demo1 {
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 79, 6666.66, Employee.Status.BUSY),
new Employee(101, "张三", 18, 9999.99, Employee.Status.FREE),
new Employee(103, "王五", 28, 3333.33, Employee.Status.VOCATION),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.BUSY),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
new Employee(105, "田七", 38, 5555.55, Employee.Status.BUSY)
);

public static void main(String[] args) {
}

@Test
public void test1() {
List<String> list = Arrays.asList("ccc", "aaa", "bbb");
list.stream().sorted().forEach(System.out::println);
}

/*
查找与匹配:
allMath:--检查是否匹配所有元素
anyMatch:--检查是否至少匹配一个元素
noneMatch:--检查是否没有匹配所有元素
findFirst--返回第一个元素
findAny--返回当前流中的任意元素
count--返回流中元素的总个数
max--返回流中最大值
min--返回流中最小值
*/
@Test
public void test12() {
boolean b1 = emps.stream().allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.print(b1);

boolean b2 = emps.stream().anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.print(b2);

boolean b3 = emps.stream().noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.print(b3);
Optional<Employee> first = emps.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).findFirst();
System.out.println(first.get());


Optional<Employee> op2 = emps.stream().filter((e) -> e.getStatus().equals(Employee.Status.BUSY))
.findAny();

System.out.println(op2.get());
}

@Test
public void test2() {


long count = emps.stream().count();

System.out.println(count);

Optional<Employee> max = emps.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(max.get());

Optional<Double> min = emps.stream().map((Employee::getSalary)).min(Double::compare);
System.out.println(min.get());


}

8 归约与收集

image-20190408082825569


image-20190408083000011

1
2
3
4
5
6
7
8
@Test
public void test3() {

Optional<Double> reduce = emps.stream().map(Employee::getSalary).reduce(Double::max);
Double aDouble = reduce.get();
System.out.println(aDouble);

}

image-20190408083402745


image-20190408084617412


1
2
3
4
5
6
7
@Test
public void test4() {
List<String> collect = emps.stream().map(Employee::getName).collect(Collectors.toList());
collect.forEach(System.out::println);
Set<String> collect1 = emps.stream().map(Employee::getName).collect(Collectors.toSet());
collect1.forEach(System.out::println);
}

image-20190408084918406


image-20190408085115683


image-20190408085851699


image-20190408085904787


9